<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\admin\model\UserDepart;
use fast\Tree;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';
	protected $noNeedRight = ['depart'];

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
	protected $grouplist = [];
    protected $groupdata = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
		$groupList = collection(UserDepart::column('id,pid,name'))->toArray();

        Tree::instance()->init($groupList);
        $groupList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
		
        $groupName = [0 => __('None')];
        foreach ($groupList as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }

        $this->grouplist = $groupList;
        $this->groupdata = $groupName;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
			$map = [];
			$groupIds = $this->auth->getGroupIds();
			if($groupIds[0] == 3)
			{
				$map['depart_id'] = $this->auth->depart_id;
			}
            $list = $this->model
                ->with('group')
                ->where($where)
				->where($map)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
				$depart = UserDepart::get($v->depart_id);
				$v->depart_id = $depart['name']??'';
				if($v->sub_depart)
				{
					$sub_depart = UserDepart::get($v->sub_depart);
					$v->depart_id .= '/'.$sub_depart['name'];
				}
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
			
			$params = $this->request->post("row/a");
			$depart_id = $params['depart_id'];
			$depart = model('UserDepart')->get($depart_id);
			if($depart['pid'] == 0)
			{
				$params['sub_depart'] = 0;
			}
			else
			{
				$params['depart_id'] = $depart['pid'];
				$params['sub_depart'] = $depart_id;
			}
			
			if(!$params['password']) 
			{
				$salt = \fast\Random::alnum();
                $params['password'] = \app\common\library\Auth::instance()->getEncryptPassword('123456', $salt);
                $params['salt'] = $salt;
			}
			else
			{
				$salt = \fast\Random::alnum();
                $params['password'] = \app\common\library\Auth::instance()->getEncryptPassword($params['password'], $salt);
                $params['salt'] = $salt;
			}
			$this->request->post(array('row'=>$params));
        }
		
		$this->view->assign('groupList', build_select('row[depart_id]', $this->groupdata, [], ['class'=>'form-control selectpicker', 'data-rule'=>'required']));
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
			
			$params = $this->request->post("row/a");
			$depart_id = $params['depart_id'];
			$depart = model('UserDepart')->get($depart_id);
			if($depart['pid'] == 0)
			{
				$params['sub_depart'] = 0;
			}
			else
			{
				$params['depart_id'] = $depart['pid'];
				$params['sub_depart'] = $depart_id;
			}
			$this->request->post(array('row'=>$params));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
		
		$this->view->assign('groupList', build_select('row[depart_id]', $this->groupdata, $row['depart_id'], ['class'=>'form-control selectpicker', 'data-rule'=>'required']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

	public function depart()
	{
		$groupList = collection(UserDepart::column('id,pid,name'))->toArray();

        Tree::instance()->init($groupList);
        $groupList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
		
        $groupName = [];
        foreach ($groupList as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }
		
		echo json_encode($groupName);
		exit;
	}
}
